/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is the "Foxmon" extension for Firefox.
*
* The developer of the Original Code is Saravana Kumar.
*
* Portions created by the Initial Developer are 
* Copyright (C) 2006 the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*   Saravana Kumar <saravanannkl@gmail.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
* ***** END LICENSE BLOCK ***** */

function Foxmon_generateReport() {
    var lstReports = document.getElementById("lstReports");
    var txtStartDate = document.getElementById("txtStartDate");
    var txtEndDate = document.getElementById("txtEndDate");
    var sqlAppendCondition = '';
    
    if(txtStartDate.value.length > 0) {
        sqlAppendCondition = " ID > " + Date.parse(txtStartDate.value);
    } 
    
    if(txtEndDate.value.length > 0) {
        if(sqlAppendCondition.length>0)
            sqlAppendCondition += " AND ";
        sqlAppendCondition += " ID < " + (Date.parse(txtEndDate.value)+86400000);
    }
    
    var lstDays = document.getElementById('lstDays');
    var selectedDays = [];
    for(var i=0;i<lstDays.options.length; i++) {
		if(lstDays.options[i].selected)
			selectedDays[selectedDays.length] = lstDays.options[i].value;
    }
    
    if(selectedDays.length>0) {
	if(sqlAppendCondition.length>0)
        	sqlAppendCondition += " AND ";
        sqlAppendCondition += " DayOfWeek in (" + selectedDays + ")";
    }
    
    switch(lstReports.value) {
        case "1":
            Foxmon_generateHourlyActivityReport(sqlAppendCondition);
            break;
        default:
            alert("Select a report");
            break;
    }
}

function Foxmon_generateHourlyActivityReport(sqlAppendCondition) {
	var divRptArea = document.getElementById('divReportArea');
	var HOURLY_RPT_COLUMNS = ["Year", "Month", "Day", "Day Of Week"];
	var WEEK_DAYS = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
	var hours = [], days = [];
    
    	try {
		if(sqlAppendCondition.length>0)
		    sqlAppendCondition = " where " + sqlAppendCondition;

		hours = FoxmonStorageHelper.executeQuery("select Hour, round(sum(HourlyPageVistTime)/60.0, 0) TotalDuration, round(sum(HourlyPageVistTime)/(count(*) * 60.0), 0) AverageDuration from (select Year, Month, Day, Hour, sum(PageVisitDuration) HourlyPageVistTime from BrowsingHistory " + sqlAppendCondition + " group by Year, Month, Day, Hour) group by Hour order by Hour; ");
		days = FoxmonStorageHelper.executeQuery("select Year, Month, Day, DayOfWeek, round(sum(PageVisitDuration)/60.0, 0) Time  from BrowsingHistory " + sqlAppendCondition + " group by Year, Month, Day order by Year, Month, Day;");
		detailReport = FoxmonStorageHelper.executeQuery("select Year, Month, Day, Hour, round(sum(PageVisitDuration)/60.0, 0) Time  from BrowsingHistory " + sqlAppendCondition + " group by Year, Month, Day, Hour order by Year, Month, Day, Hour;");

		var reportTable = document.createElement('table');
		var reportHeader = document.createElement('thead');
		var reportHeaderRow = document.createElement('tr');
		var reportBody = document.createElement('tbody');

		Foxmon_createAndAppendTableCell(reportHeaderRow, "tdReportHeaderCellDate", "Date");

		for(var i=0; i<hours.length; i++)
			Foxmon_createAndAppendTableCell(reportHeaderRow, "tdReportHeaderCell" + hours[i][0], hours[i][0]<12 ? hours[i][0] +  " AM" :  (hours[i][0]==12 ? 12 : hours[i][0]-12) +  " PM");

		Foxmon_createAndAppendTableCell(reportHeaderRow, "tdReportHeaderCellTotal", "Total Hours");

		reportHeader.appendChild(reportHeaderRow);
		reportTable.appendChild(reportHeader);
		reportHeaderRow = null;
		reportHeader = null;
        
		for(var i=0; i<days.length; i++) {
		    var reportDataRow = document.createElement('tr');
		    var date = days[i][0]+ "/" + days[i][1] + "/" + days[i][2];
		    var currentDateString = (new Date(Date.parse(date))).toLocaleString();

		    /*
		    for(var j=0; j<HOURLY_RPT_COLUMNS.length-1;j++)
			Foxmon_createAndAppendTableCell(reportDataRow, "tdReportCell" + HOURLY_RPT_COLUMNS[j] + date, days[i][j]);

		    Foxmon_createAndAppendTableCell(reportDataRow, "tdReportCell" + HOURLY_RPT_COLUMNS[HOURLY_RPT_COLUMNS.length-1] + date, WEEK_DAYS[days[i][HOURLY_RPT_COLUMNS.length-1]]);
		    */

		    Foxmon_createAndAppendTableCell(reportDataRow, "tdReportCellDate" + date, currentDateString.substring(0, currentDateString.length-12));

		    for(var j=0; j<hours.length;j++)
					Foxmon_createAndAppendTableCell(reportDataRow, "tdReportCell" + date + "/" + hours[j][0], "--");

		    FoxmonLogger.Log(date + ' - ' + i + ' - ' + days[i][4]);
		    Foxmon_createAndAppendTableCell(reportDataRow, "tdReportCellTotal-" + date, FoxmonHelper.ConvertDecimalHoursToHHMM(FoxmonHelper.Round(days[i][4]/60.0)));
		    reportBody.appendChild(reportDataRow);
		    reportDataRow = null;
		}

		var reportDataTotalDurationRow = document.createElement('tr');
		var reportDataAvgDurationRow = document.createElement('tr');

		Foxmon_createAndAppendTableCell(reportDataTotalDurationRow, "tdReportCellTotalDuration", "Total Time");
		Foxmon_createAndAppendTableCell(reportDataAvgDurationRow, "tdReportCellAvgDuration", "Average Time");
			//reportDataTotalDurationRow.lastChild.setAttribute('colspan', 3);
			//reportDataAvgDurationRow.lastChild.setAttribute('colspan', 3);

			var totalTime = 0;
			for(var i=0; i<hours.length; i++) {
				Foxmon_createAndAppendTableCell(reportDataTotalDurationRow, "tdReportCellTotalDuration" + hours[i][0], hours[i][1]);
				totalTime += hours[i][1];
				Foxmon_createAndAppendTableCell(reportDataAvgDurationRow, "tdReportCellAvgDuration" + hours[i][0], hours[i][2]);
		}
		Foxmon_createAndAppendTableCell(reportDataTotalDurationRow, "tdReportCellTotalDurationTotalTime", FoxmonHelper.ConvertDecimalHoursToHHMM(FoxmonHelper.Round(totalTime/60.0)));
		Foxmon_createAndAppendTableCell(reportDataAvgDurationRow, "tdReportCellTotalAvgDuration", FoxmonHelper.ConvertDecimalHoursToHHMM(FoxmonHelper.Round(totalTime/(days.length * 60.0))));

		reportBody.appendChild(reportDataTotalDurationRow);
		reportBody.appendChild(reportDataAvgDurationRow);
		reportDataTotalDurationRow = null;
		reportDataAvgDurationRow = null;

		reportTable.appendChild(reportBody);
		reportBody = null;
		divRptArea.innerHTML = "";
		divRptArea.appendChild(reportTable);
		reportTable = null;

		for(var i=0;i<detailReport.length;i++) {
			var id = "tdReportCell" + detailReport[i][0] + "/" + detailReport[i][1] + "/" + detailReport[i][2] + "/" + detailReport[i][3];
			var time = detailReport[i][4];
			var tdReportCell = document.getElementById(id);
			if(tdReportCell) {
				tdReportCell.innerHTML = time;
				if(time>15)
					tdReportCell.className = "highlight";
			}
			else
				FoxmonLogger.Log("Missing Cell with ID: " + id);
		}
	    }
	    catch(ex) {
	      FoxmonLogger.LogError(ex);
	    }
}

function Foxmon_createAndAppendTableCell(row, id, innerHTML) {
	Foxmon_createAndAppendChild(row, "td", id, innerHTML);
}

function Foxmon_createAndAppendChild(parent, childTagName, id, innerHTML) {
	var childNode = document.createElement(childTagName);
	childNode.id = id;
	childNode.innerHTML = innerHTML;
	parent.appendChild(childNode);
	childNode = null;
}
